#include "downloadmanager.h"

DownloadManager::DownloadManager(QObject *parent) :
    QObject(parent)
{
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));
    prevProgress = 0;
}

DownloadManager::~DownloadManager()
{
    manager->disconnect();
    delete manager;
}

QNetworkRequest::Priority DownloadManager::convertPriority(int priority)
{
    switch(priority) {
    case 1: return QNetworkRequest::HighPriority;
    case 5: return QNetworkRequest::LowPriority;
    default: return QNetworkRequest::NormalPriority;
    }
}

void DownloadManager::startDownload(QString url, QString folder, int priority, int id)
{

    QNetworkRequest request = QNetworkRequest(QUrl(url));
    url2folder.insert(url, folder);
    request.setPriority(convertPriority(priority));
    currentDownload = manager->get(request);
    currentDownload->setProperty("id", id);
    connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
                SLOT(downloadProgress(qint64,qint64)));
}


void DownloadManager::replyFinished(QNetworkReply* reply)
{
    QString fullname = url2folder.take(reply->url().toString()).append("/").append(QFileInfo(reply->url().path()).fileName());
    QFile file(fullname);
    file.open(QIODevice::WriteOnly);
    file.write(reply->readAll());
    file.close();
    reply->deleteLater();
}

void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if (bytesReceived < 0 || bytesTotal < 0) return;
    int progress = (bytesReceived * 100)/bytesTotal;
    if(progress < 100 && progress - prevProgress < 1) return;
    prevProgress = progress;
    DatabaseManager::getDBManager()->insertProgressDownload(currentDownload->property("id").toInt(), progress);
    emit progressUpdate();
}
